import { Intersection, Object3D } from "three";
import { Editor } from "./editor.js";

export class Selector {

  editor:Editor;
	constructor( editor:Editor ) {

		const signals = editor.signals;

		this.editor = editor;

		// signals

		signals.intersectionsDetected.add( ( intersects:Intersection[] ) => {

			if ( intersects.length > 0 ) {

				const object = intersects[ 0 ].object;

				if ( object.userData.object !== undefined ) {

					// helper

					this.select( object.userData.object );

				} else {

					this.select( object );

				}

			} else {

				this.select( null );

			}

		} );

	}

	select( object?:Object3D|null ) {
		if(object===undefined){
			object=null;
		}

		if ( this.editor.selected === object ) {
			return;
		}

		// let uuid = null;

		// if ( object !== null ) {

		// 	uuid = object.uuid;

		// }

		this.editor.selected = object;
		this.editor.selectedObjects=[];
		// this.editor.config.setKey( 'selected', uuid );

		this.editor.signals.objectSelected.dispatch( object );

	}

	deselect() {

		this.select( null );

	}

	selects(object:Object3D){
		const index=this.editor.selectedObjects.findIndex((item)=>item.uuid===object.uuid);
		if(index>=0){
			// 取消选中
			this.editor.selectedObjects.splice(index,1);
		}else{
			// 选中
			this.editor.selectedObjects.push(object);
		}
		console.log('多选状态',this.editor.selectedObjects);
		
		this.editor.signals.objectSelected.dispatch( object );
	}


}